import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/circle/CircleItem.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/pages/lesson/LessonItem.dart';
import 'package:huajianshe_app/pages/lesson/model/LessonModel.dart';
import 'package:huajianshe_app/pages/main/MomentDetailPage.dart';
import 'package:huajianshe_app/pages/main/MomentItem.dart';
import 'package:huajianshe_app/pages/main/model/MomentModel.dart';
import 'package:huajianshe_app/pages/search/SearchModel.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/SearchAppBar.dart';

class SearchPage extends StatefulWidget {

  final SearchType searchType;
  final int? momentType;
  final int? circleId;
  final int? businessType; //动态类型 1.动态 2.商机 （默认全部）

  const SearchPage(this.searchType, {Key? key,
    this.momentType,
    this.circleId,
    this.businessType
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SearchPageState();
  }
}

class _SearchPageState extends BaseState<SearchPage> {

  int page = 1;
  Widget? hotAndHistoryWidget;
  String text = '';

  @override
  void initState() {
    super.initState();
    print('${widget.searchType} ${widget.momentType}');
    switch(widget.searchType) {
      case SearchType.moment:
        refresher = Refresher<MomentListData>(this);
        break;
      case SearchType.circle:
        refresher = Refresher<CircleListData>(this);
        break;
      case SearchType.friend:
        break;
      case SearchType.lesson:
        refresher = Refresher<Lesson>(this);
        break;
    }
    refresher?.enablePullDown = false;
    loadHotAndHistory();
  }

  void loadHotAndHistory() {
    int type = 0;
    if (widget.searchType == SearchType.moment) type = 4;
    if (widget.searchType == SearchType.circle) type = 3;
    if (type == 0) return;
    var data = {
      'type': type
    };
    sendReq(Api.searchHotAndHistory(), SearchHotAndHistoryResp(), data: data, doNotShowProgressBar: true);
  }

  @override
  void onLoadMore() {
    refresher?.mode = Mode.loadMore;
    doSearch(text, false);
  }

  doSearch(String text, bool reset) {
    this.text = text;
    if (reset) {
      refresher?.mode = Mode.refresh;
      page = 1;
    }
    print('do search');
    switch(widget.searchType) {
      case SearchType.moment:
        searchMoment(text);
        break;
      case SearchType.circle:
        searchCircle(text);
        break;
      case SearchType.friend:
        break;
      case SearchType.lesson:
        searchLesson(text);
        break;
    }
  }

  searchHot(String text) {
    this.text = text;
    setState(() => null);
    doSearch(text, true);
  }

  searchMoment(String text) {
    var type = widget.businessType;
    if (widget.momentType == MomentType.MOMENT_TYPE_RECOMMENDATION) {//推荐只有动态，好友里还有商机
      type = MomentBusinessType.MOMENT;
    }
    var data = {
      'page': page,
      'list_rows': 10,
      'get_type':  widget.momentType,
      'type': type,
      'circle_id': widget.circleId,
      'search_data': text
    };
    sendReq(Api.momentList(), MomentListResp(), data: data, doNotShowProgressBar: doNotShowProgressBar);
  }

  searchCircle(String text) {
    var data = {
      'page': page,
      'list_rows': 10,
      'search_data': text
    };
    sendReq(Api.circleList(), CircleListResp(), data: data);
  }

  searchLesson(String text) {
    var data = {
      'list_rows': 10,
      'page': page,
      'lesson_type': 2,
      'search_data': text
    };
    sendReq(Api.lessonList(), LessonListResp(), data: data, doNotShowProgressBar: true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is SearchHotAndHistoryResp) {
      hotAndHistoryWidget = buildHotAndHistory(t);
      setState(() => null);
    }
    if (t is MomentListResp) {
      refresher?.load(t.data?.data);
      setState(() => {});
      page++;
    } else if (t is CircleListResp) {
      refresher?.load(t.data?.data);
      setState(() => {});
      page++;
    } else if (t is LessonListResp) {
      refresher?.load(t.data?.data);
      setState(() => {});
      page++;
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: SearchAppBar(widget.searchType, this.doSearch, text: this.text),
      body: ColoredBox(color: Colors.transparent, child: Padding(padding: EdgeInsets.all(15), child:
          refresher?.build(buildChild())
        ))
    );
  }

  Widget? buildChild() {
    print('11');
    Widget? child = buildEmptyPage();
    if (child != null) {
      print('3');
      return hotAndHistoryWidget ?? child;
      // if (hotAndHistoryWidget != null) {
      //   return hotAndHistoryWidget;
      // }
      // return child;
    }
    print('2');
    return
      ListView.separated(
          itemBuilder: (_, index) {
            return buildItem(index);
          },
          separatorBuilder: (_, index) => H(10),
          itemCount: (refresher?.data?.length ?? 0)
      );
  }

  Widget buildItem(int index) {
    switch(widget.searchType) {
      case SearchType.moment:
        CircleInfo? circleInfo = getCircle(refresher?.data?[index]);
        return MomentItem(refresher?.data?[index], circleInfo, onComment: onComment);

      case SearchType.circle:
        return CircleItem(refresher?.data?[index]);

      case SearchType.friend:
      break;
      case SearchType.lesson:
        return LessonItem(refresher?.data?[index]);
    }
    return H(0);
  }

  Widget buildHotAndHistory(SearchHotAndHistoryResp resp) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text('热门搜索', style: TS(12, C.gray666)),
      H(12),
      Wrap(spacing: 15, runSpacing: 10, children: [
        ...resp.data?.hot?.map((e) {
          // return Container(child: Text('${e.name}')) ;
          return SmartButton(text: e.name ?? '', fontSize: 13, textColor: C.gray333, height: 30, radius: 15, padding: EdgeInsets.symmetric(horizontal: 15),
            backgroundColor: C.grayF6, borderColor: Colors.transparent, inWrap: true, onPressed: () { this.searchHot(e.name ?? ''); },);
        }).toList() ?? [H(0)]
      ],),
      H(30),
      Text('历史搜索', style: TS(12, C.gray666)),
      H(12),
      Wrap(spacing: 15, runSpacing: 10, children: [
        ...resp.data?.mine?.map((e) {
          return SmartButton(text: e.name ?? '', fontSize: 13, textColor: C.gray333, height: 30, radius: 15, padding: EdgeInsets.symmetric(horizontal: 15),
            backgroundColor: C.grayF6, borderColor: Colors.transparent, inWrap: true, onPressed: () { this.searchHot(e.name ?? ''); });
        }).toList() ?? [H(0)]
      ],),
    ],);
  }

  CircleInfo? getCircle(MomentListData? data) {//如果是推荐列表，需要取出圈子信息传到个人主页
    CircleInfo? circleInfo;
    if (widget.momentType == MomentType.MOMENT_TYPE_RECOMMENDATION) {
      if ((data?.circles?.length ?? 0) > 0) {
        circleInfo = data?.circles?[0];
      }
    }
    return circleInfo;
  }

  void onComment(MomentListData? data) {
    DialogUtil.showBottomDialogV2(context, MomentDetailPage(data, getCircle(data)), height: 0.8,
        radius: 13, cornerPosition: 3, margin: EdgeInsets.symmetric(horizontal: 5));
  }
}

enum SearchType {
  circle, moment, friend, lesson
}